package cn.zl.rtsp.handler;

import cn.zl.rtsp.session.RTSPSession;
import cn.zl.common.util.ChannelUtils;
import cn.zl.rtsp.constant.RTSPConstant;
import cn.zl.rtsp.response.RTSPResponse;
import cn.zl.rtsp.response.RTSPResponseFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.UUID;

public class RTSPHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(RTSPHandler.class);



    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        RTSPSession session = channel.attr(RTSPConstant.SESSION_KEY).get();
        if(session == null) {
            session = new RTSPSession();
            session.id(UUID.randomUUID().toString());
            session.channel(channel);
            channel.attr(RTSPConstant.SESSION_KEY).set(session);
        }
        logger.info("channelActive session,IP=[{}],session:{}", ChannelUtils.getIp(channel), session);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("exceptionCaught", cause);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof DefaultHttpRequest req) {
            HttpMethod method = req.method();
            String methodName = method.name();
            logger.info("request {}\n{}", methodName, req);
            Optional<RTSPResponse> optional = RTSPResponseFactory.create(methodName, ctx, req);
            if (optional.isEmpty()) {
                return;
            }
            RTSPResponse response = optional.get();
            response.decode();
            response.write();
            response.after();
        } else if (msg instanceof HttpContent content) {
            if (content.content().isReadable()) {
                /* 此时, 才表示HttpContent是有内容的, 否则,它是空的, 不需要处理 */
                logger.info("HttpContent no handler");
            }
        } else {
            logger.info("no handler");
        }
    }

}
